<?php

namespace app\common\model;

use think\Model;


class Address extends Model
{





    // 表名
    protected $name = 'address';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];

    protected static function init()
    {
        self::event('before_update', function ($obj) {
            $changed = $obj->getChangedData();
            if (array_key_exists('is_default', $changed)) {
                if ($obj->is_default == 1) {
                    self::update(['is_default' => 0], ['user_id' => $obj->user_id], 'is_default');
                }
            }
            //更新坐标
            if (array_key_exists('address', $changed) || array_key_exists('citys', $changed)) {
                if ($obj->citys && $obj->address && !$obj->lat) {
                    $lang = get_address_code(str_replace(',', '', $obj->citys) . $obj->address);
                    if (isset($lang['status']) && !empty($lang['geocodes'][0])) {
                        $arr = explode(',', $lang['geocodes'][0]['location']);
                        $obj->lng = $arr[0];
                        $obj->lat = $arr[1];
                    }
                }
            }
        });


        self::event('before_insert', function ($obj) {

            if (isset($obj->is_default) && $obj->is_default == 1) {
                self::update(['is_default' => 0], ['user_id' => $obj->user_id], 'is_default');
            }

            if (isset($obj->address) && $obj->address && !$obj->lat) {
                $lang = get_address_code(str_replace(',', '', $obj->citys) . $obj->address);
                if (isset($lang['status']) && !empty($lang['geocodes'][0])) {
                    $arr = explode(',', $lang['geocodes'][0]['location']);
                    $obj->lng = $arr[0];
                    $obj->lat = $arr[1];
                }
            }
        });
    }
}
